import React,{Component} from 'react'
import SQLiteStorage from 'react-native-sqlite-storage';

SQLiteStorage.DEBUG(true);
var database_name = "water.db";
var database_version = "2.0";
var database_displayname = "MySQLite";
var database_size = -1;
var db;
const SysConfig_TABLE_NAME = "sys_config";

export default class SQLite extends Component{

    render(){
        return null;
    }
	
    componentWillUnmount(){
        if(db){
            this._successCB('close');
            db.close();
        }else {
            console.log("SQLiteStorage not open");
        }
    }
	
    open(){
        db = SQLiteStorage.openDatabase(
            database_name,
            database_version,
            database_displayname,
            database_size,
            ()=>{
                this._successCB('open');
            },
            (err)=>{
                this._errorCB('open',err);
            });
    }
	
    createTable(){
        this.createSysConfigTable();
		var result=this.findTableExist(SysConfig_TABLE_NAME);
		if(result<=0){
			this.createSysConfigTable();
		}
    }
	
	createSysConfigTable(){
		if (!db) {
            this.open();
        }
        //创建表
        db.transaction((tx)=> {
			var createSql='CREATE TABLE IF NOT EXISTS ' + SysConfig_TABLE_NAME + '(' +
                'id integer PRIMARY KEY,' +
                'host INTEGER'
                + ');'
            tx.executeSql(createSql, [], ()=> {
                    this._successCB('executeSql');
                }, (err)=> {
                    this._errorCB('executeSql', err);
            	}
			);
		}, (err)=> {
            this._errorCB('transaction', err);
        }, ()=> {
            this._successCB('transaction');
        })
	}
	
	saveSysConfig(sysConfig){//保存抄表册记录
        return new Promise((resolve, reject)=>{
            if(db){
				db.executeSql('INSERT INTO '+SysConfig_TABLE_NAME+' (id,host) VALUES(?,?)',
					[sysConfig.getId(),sysConfig.getHost()],
					()=>{
						this._successCB('save '+SysConfig_TABLE_NAME);
						resolve();
					},
					(err)=>{
						this._errorCB('save '+SysConfig_TABLE_NAME,err);
						reject();
					}
				)
            }else {
                reject('db not open');
            }
        });

    }
	
	dropTable(){    
		db.transaction((tx)=>{      
			tx.executeSql('drop table '+SysConfig_TABLE_NAME,[],
				()=>{       });    
			},(err)=>{      
				this._errorCB('transaction', err);    
			},()=>{      
				this._successCB('transaction');    
		}); 
	}
	
	deleteSysConfig(){//删除记录
        return new Promise((resolve, reject)=>{
            if(db){
                db.executeSql('DELETE FROM '+SysConfig_TABLE_NAME,[],
                    ()=>{
                        resolve();
                        this._successCB('deleteSysConfig');
                    },(err)=>{
                        reject(err);
                        this._errorCB('deleteSysConfig',err);
                    });
            }else {
                reject('db not open');
            }
        });

    }

	findSysConfigById(id){//获取cost_master记录
        return new Promise((resolve, reject)=>{
            if(db){
                db.executeSql('SELECT * FROM '+SysConfig_TABLE_NAME +' WHERE id=?',[id],
                    (results)=>{
                        if(results.rows.length > 0){
                            resolve(results.rows.item(0));
                        }else {
                            reject('not find item');
                        }
                        this._successCB('findSysConfigById')
                    },(err)=>{
                        reject(err);
                        this._errorCB('findSysConfigById',err)
                    });
            }else {
                reject('db not open');
            }
        });
    }
	
	findTableExist(tableName){
		return new Promise((resolve, reject)=>{
            if(db){
                db.executeSql("select count(*) from sqlite_master where type='table' and name =?",[tableName],
                    (results)=>{
                        if(results.rows.length > 0){
                            resolve(results.rows.item(0));
                        }else {
                            reject('findTableExist not find item');
                        }

                        this._successCB('findTable')
                    },(err)=>{
                        reject(err);
                        this._errorCB('findTable',err)
                    });
            }else {
                reject('db not open');
            }
        });
	}
	
	updateSysConfig(sysConfig){//更新记录
        return new Promise((resolve, reject)=>{
            if(db) {
				db.executeSql('UPDATE ' + SysConfig_TABLE_NAME + ' SET host=? WHERE id="' + sysConfig.getId()+'"',
                    [sysConfig.getHost()],
                    ()=> {
                        this._successCB('updateSysConfig');
                        resolve();
                    },
                    (err)=> {
                        this._errorCB('updateSysConfig', err);
                        reject(err);
                    });
            }else{
                reject('db not open');
            }
        });
    }
	
    listCostMaster(pageSize,index){//获取cost_master记录列表
        return new Promise((resolve, reject)=>{
            if(db){
                db.executeSql('SELECT * FROM '+CostMaster_TABLE_NAME +' LIMIT '+pageSize+' OFFSET '+((index-1)*pageSize),[],
                    (results)=>{
                        var len = results.rows.length;
                        var datas = [];
                        for(let i=0;i<len;i++){
                            datas.push(results.rows.item(i));
                        }
                        resolve(datas);
                        this._successCB('listCostMaster');
                    },(err)=>{
                        reject(err);
                        this._errorCB('listCostMaster',err);
                    });
            }else {
                reject('db not open');
            }
        });
    }
	
    close(){
        if(db){
            this._successCB('close');
            db.close();
        }else {
            console.log("SQLiteStorage not open");
        }
        db = null;
    }
	
    _successCB(name){
        console.log("SQLiteStorage "+name+" success");
    }
	
    _errorCB(name, err){
        console.log("SQLiteStorage "+name+" error:"+JSON.stringify(err));
    }
}

